package com.ruikong.dazhi.service.impl.baseinfo;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.ruikong.dazhi.controller.result.BaseResult;
import com.ruikong.dazhi.controller.result.ResultApi;
import com.ruikong.dazhi.dao.base.PersonnelMapper;
import com.ruikong.dazhi.dao.basicinfo.LineMapper;
import com.ruikong.dazhi.dao.basicinfo.ShopMapper;
import com.ruikong.dazhi.entity.base.Personnel;
import com.ruikong.dazhi.entity.basicinfo.Line;
import com.ruikong.dazhi.entity.basicinfo.Shop;
import com.ruikong.dazhi.model.input.LinePageInput;
import com.ruikong.dazhi.model.output.LineOutput;
import com.ruikong.dazhi.model.output.ShopLineOutput;
import com.ruikong.dazhi.service.basicinfo.ILineService;
import com.ruikong.dazhi.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (Line)表服务实现类
 *
 * @author Hassion.Tang
 * @since 2020-07-01 14:34:15
 */
@Service("lineService")
public class LineServiceImpl implements ILineService {
    @Autowired
    private LineMapper lineMapper;


    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private PersonnelMapper personnelMapper;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Line queryById(Integer id) {
        return this.lineMapper.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Line> queryAllByLimit(int offset, int limit) {
        return this.lineMapper.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param line 实例对象
     * @return 实例对象
     */
    @Override
    public Integer insert(Line line) {
        return this.lineMapper.insert(line);

    }

    /**
     * 修改数据
     *
     * @param line 实例对象
     * @return 实例对象
     */
    @Override
    public Integer update(Line line) {

        return this.lineMapper.update(line);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.lineMapper.deleteById(id) > 0;
    }

    @Override
    public PageInfo<Line> getLinePageInfo(LinePageInput input) {
        List<Personnel> personnels = personnelMapper.getShowAllPersonnelList();
        List<Shop> shops = shopMapper.queryAllTree();
        PageHelper.startPage(input.getPageNumber(), input.getPageSize());
        List<Line> lineLists = this.lineMapper.getLineListSearch(input);
        for (Line l : lineLists) {
            List<Personnel> showPersonnel = new ArrayList<>();
            if(l.getUser_id() != null){
                showPersonnel =  personnels.stream().filter(x->l.getUser_id().equals(x.getUserId())).collect(Collectors.toList());
            }
            Personnel personnel = showPersonnel!=null && showPersonnel.size()>0?showPersonnel.get(0):null;
            if (personnel != null) {
                l.setUserName(personnel.getPersonnelName());
                List<Shop> showShops = shops.stream().filter(x->x.getId().equals(l.getShop_id())).collect(Collectors.toList());
                l.setShopName(showShops!=null && showShops.size()>0?showShops.get(0).getShopName():"");
            }
        }
        PageInfo<Line> pageInfo = new PageInfo<>(lineLists);
        return pageInfo;
    }

    @Override
    public Integer isExist(Line line) {
        return this.lineMapper.isExist(line);
    }

    @Override
    public List<Line> getLineList() {
        return this.lineMapper.getLineList();
    }

    @Override
    public List<ShopLineOutput> getShopLineTree() {
        List<ShopLineOutput> list_tree = new ArrayList<>();
        ShopLineOutput root = new ShopLineOutput();
        root.setId(0);
        root.setName("车间产线");
        root.setpId(-1);
        root.setShopOrLine(-1);
        list_tree.add(root);

        List<Shop> list_shop = this.shopMapper.queryAllTree();
        for (Shop sp : list_shop) {
            ShopLineOutput shop = new ShopLineOutput();
            shop.setShopOrLine(0);
            shop.setId(sp.getId());
            shop.setpId(0);
            shop.setName(sp.getShopName());

            List<Line> list_line = this.lineMapper.getLineListByShop(sp.getId());
            for (Line l : list_line) {
                ShopLineOutput line = new ShopLineOutput();
                line.setShopOrLine(1);
                line.setId(l.getId());
                line.setpId(sp.getId());
                line.setName(l.getLine_name());
                list_tree.add(line);
            }
            list_tree.add(shop);
        }
        return list_tree;
    }

    @Override
    public List<Line> getLineListByShop(Integer id) {
        return this.lineMapper.getLineListByShop(id);
    }

    @Override
    public List<Line> getLineByLineType(Integer lineType) {
        return this.lineMapper.getLineListByType(lineType);
    }

    @Override
    public List<LineOutput> getPackageOrderNumberByLine() {
        boolean  blOrderExists = false;
        // 排产产线
        List<LineOutput> list = lineMapper.getPackageOrderNumberByLine();
        // 所有产线
        List<LineOutput> name = lineMapper.getLineNameByState();

        for (LineOutput nameList : name) {
            int unDoneNumber = 0;
            int doneNumber = 0;
            blOrderExists = false;
            for (LineOutput listNumber : list) {
                if (nameList.getLine_id() == listNumber.getLine_id()) {
                    blOrderExists = true;
                    if (listNumber.getOrder_state() == 2 || listNumber.getOrder_state() == 3) {
                        unDoneNumber += listNumber.getPlanNumber();
                    } else if (listNumber.getOrder_state() == 4) {
                        doneNumber += listNumber.getPlanNumber();
                    }

                }
            }
            if(blOrderExists)
            {
                nameList.setDoneNumber(doneNumber);
                nameList.setUnDoneNumber(unDoneNumber);
            }
            else
            {
                nameList.setUnDoneNumber(0);
                nameList.setDoneNumber(0);
            }

        }
        return name;
    }

    @Override
    public List<LineOutput> getLineNameByState() {
        return this.lineMapper.getLineNameByState();
    }

    @Override
    public BaseResult lineImport(MultipartFile multipartFile, Integer personnelId) {
        BaseResult baseResult = new BaseResult();
        //车间集合
        List<Line> lineList = new ArrayList<>();
        try {
            //将multipartFileToFile转化为File
            File file = ExcelUtil.multipartFileToFile(multipartFile);
            InputStream inputStream = new FileInputStream(file);
            String fileName = file.getName();
            String suffix = fileName.split("\\.")[1];
            if (!suffix.equals("xlsx") && !suffix.equals("xls")) {
                baseResult.setMsg("错误！提交文件格式不正确，请上传excel文件");
                baseResult.setCode(ResultApi.failCode);
                return baseResult;
            }
            //xlsx文件使用XSSFWorkbook，否则使用HSSFWorkbook
            Workbook workbook = suffix.equals("xlsx") ? new XSSFWorkbook(inputStream) : new HSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            Cell cell = null;
            Row row = null;
            Iterator<Row> iterator = sheet.rowIterator();
            int index = 0;
            while (iterator.hasNext()) {
                row = iterator.next();
                //跳过第一行标题行
                if (0 == index) {
                    index++;
                    continue;
                }
                //产线
                Line line = new Line();
                //产线编号
                cell = row.getCell(0);
                String line_sn;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，产线编号不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    line_sn = cell.getStringCellValue().trim();
                    if(lineMapper.isLineExist(line_sn) > 0){
                        baseResult.setMsg(String.format("错误！表格第%s行，产线编号已存在", index + 1));
                        baseResult.setCode(ResultApi.failCode);
                        file.delete();
                        return baseResult;
                    }else {
                        line.setLine_sn(line_sn);
                    }
                }
                //产线名称
                cell = row.getCell(1);
                String line_name;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，产线名称不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    line_name = cell.getStringCellValue().trim();
                    line.setLine_name(line_name);
                }

                //所属车间
                cell = row.getCell(2);
                String shop_name;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，所属车间不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    shop_name = cell.getStringCellValue().trim();
                    Shop shop = this.shopMapper.queryShopByName(shop_name);
                    if (shop == null) {
                        baseResult.setMsg(String.format("错误！表格第%s行，所属车间不存在", index + 1));
                        baseResult.setCode(ResultApi.failCode);
                        file.delete();
                        return baseResult;
                    } else {
                        line.setShop_id(shop.getId());
                    }
                }
                //产线描述
                cell = row.getCell(3);
                String line_desc;
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    line_desc = cell.getStringCellValue().trim();
                    line.setLine_desc(line_desc);
                }
                //创建时间
                cell = row.getCell(4);
                Date createTime;
                if (cell != null) {
                    createTime = cell.getDateCellValue();
                    line.setCreate_time(createTime);
                }else{
                    //创建时间不填
                    //以当前时间为准
                    line.setCreate_time(new Date());
                }

                //创建人
                cell = row.getCell(5);
                String personByName;
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    personByName = cell.getStringCellValue().trim();
                    Personnel personnel  = this.personnelMapper.queryPersonByName(personByName);
                    if(personnel == null){
                        baseResult.setMsg(String.format("错误！表格第%s行，创建人不存在", index + 1));
                        baseResult.setCode(ResultApi.failCode);
                        file.delete();
                        return baseResult;
                    }else {
                        line.setUser_id(personnel.getPersonnelId());
                    }
                }else {
                    line.setUser_id(personnelId);
                }
                //备注
                cell = row.getCell(6);
                String remarks;
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    remarks = cell.getStringCellValue().trim();
                    line.setRemarks(remarks);
                }
                //状态
                line.setState(1);

                lineList.add(line);
                index++;
            }
            baseResult = this.importSave(lineList);
            file.delete();
        } catch (Exception e) {
            baseResult.setCode(ResultApi.errorCode);
            baseResult.setMsg("车间导入时出错");
            e.printStackTrace();
        }
        return baseResult;
    }

    //导入信息保存
    public BaseResult importSave(List<Line> lineList) {
        BaseResult baseResult = new BaseResult();
        Shop shop = new Shop();
        try {
            for (int i = 0; i < lineList.size(); i++) {
                Line lineSave = lineList.get(i);
                this.lineMapper.insert(lineSave);
            }
            baseResult.setMsg("导入成功");
            baseResult.setCode(ResultApi.successCode);
        } catch (Exception e) {
            baseResult.setMsg("导入时出错");
            baseResult.setCode(ResultApi.failCode);
            e.printStackTrace();
        }
        return baseResult;
    }

}